<template>
  <div>
    <n-grid :cols="4" :x-gap="12" :y-gap="12">
      <n-grid-item v-for="card in cards" :key="card.title">
        <n-card :title="card.title" size="small" :class="{ 'error-card': card.title === '失败' && card.value > 0 }">
          <div class="metric" :class="{ 'error-metric': card.title === '失败' && card.value > 0 }">{{ card.value }}</div>
        </n-card>
      </n-grid-item>
    </n-grid>

    <n-card title="任务详情" size="small" style="margin-top:12px" v-if="errorTasks.length > 0">
      <n-alert type="error" style="margin-bottom:12px">
        发现 {{ errorTasks.length }} 个任务有错误
      </n-alert>
      <n-space vertical>
        <div v-for="task in errorTasks" :key="task.id" class="error-task">
          <n-tag type="error">{{ task.name }}</n-tag>
          <span style="margin-left:8px;color:#666">{{ task.lastErrorMsg || '未知错误' }}</span>
          <n-button size="tiny" type="primary" ghost style="margin-left:8px" @click="goToTask(task.id)">查看</n-button>
        </div>
      </n-space>
    </n-card>

    <n-card title="近期处理趋势（示意）" size="small" style="margin-top:12px">
      <div id="chart" style="height:260px"></div>
    </n-card>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { NGrid, NGridItem, NCard, NAlert, NSpace, NTag, NButton } from 'naive-ui'
import * as echarts from 'echarts'
import axios from 'axios'

const router = useRouter()
const cards = ref([
  { title: '总任务', value: 0 },
  { title: '运行中', value: 0 },
  { title: '停止', value: 0 },
  { title: '失败', value: 0 }
])
const errorTasks = ref<any[]>([])

async function loadStats() {
  try {
    const { data } = await axios.get('/api/tasks')
    cards.value[0].value = data.length
    cards.value[1].value = data.filter((t:any) => t.status === 'RUNNING').length
    cards.value[2].value = data.filter((t:any) => t.status === 'STOPPED').length

    // 查找有错误的任务（有失败次数或错误消息的）
    const tasksWithErrors = data.filter((t:any) => (t.failed && t.failed > 0) || (t.lastErrorMsg && t.lastErrorMsg !== 'null'))
    cards.value[3].value = tasksWithErrors.reduce((sum:number, t:any) => sum + (t.failed || 0), 0)
    errorTasks.value = tasksWithErrors

    // 更新图表数据
    updateChart(data)
  } catch (e) {
    console.error('Failed to load stats:', e)
  }
}

function goToTask(taskId: number) {
  router.push('/tasks')
}

function updateChart(tasks: any[]) {
  const el = document.getElementById('chart')
  if (el) {
    const chart = echarts.init(el)

    // 计算真实的统计数据
    const totalProcessed = tasks.reduce((sum, task) => sum + (task.processed || 0), 0)
    const totalFailed = tasks.reduce((sum, task) => sum + (task.failed || 0), 0)

    // 模拟时间序列数据（实际项目中应该从后端获取历史数据）
    const processedData = [
      Math.max(0, totalProcessed - 50),
      Math.max(0, totalProcessed - 40),
      Math.max(0, totalProcessed - 30),
      Math.max(0, totalProcessed - 20),
      Math.max(0, totalProcessed - 10),
      totalProcessed
    ]

    const failedData = [
      Math.max(0, totalFailed - 5),
      Math.max(0, totalFailed - 4),
      Math.max(0, totalFailed - 3),
      Math.max(0, totalFailed - 2),
      Math.max(0, totalFailed - 1),
      totalFailed
    ]

    chart.setOption({
      tooltip: { trigger: 'axis' },
      legend: { data: ['处理量', '失败量'] },
      xAxis: { type: 'category', data: ['-5m','-4m','-3m','-2m','-1m','now'] },
      yAxis: { type: 'value' },
      series: [
        { name: '处理量', type: 'line', data: processedData, smooth: true },
        { name: '失败量', type: 'line', data: failedData, smooth: true }
      ]
    })
  }
}

onMounted(async () => {
  await loadStats()
})
</script>
<style scoped>
.metric { font-size: 24px; font-weight: bold; color: var(--primary-color); }
.error-metric { color: #f56565 !important; }
.error-card { border-color: #f56565; }
.error-task { display: flex; align-items: center; padding: 8px; background: #fef5e7; border-radius: 4px; }
</style>

